<script lang="ts">
import dayjs from 'dayjs';
import { Component, Inject, Vue, Watch } from 'vue-facing-decorator';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getNovelById, updateNovelTags, createChapter, updateNovelDescription, updateNovelCover, updateNovelTitle, addFavorite, removeFavorite, deleteNovel } from '@/api/novel/novel';
import type { NovelInfo, CreateChapterFormData } from '@/api/novel/novel';
import UserLink from '@/pages/profile/component/UserLink.vue';
import TextEditor from '@/components/editor/TextEditor.vue';
import type { UserInfo } from '@/api/auth/auth';
import NovelTag from '../component/NovelTag.vue';
import { uploadFile } from '@/util/fileUtil';
import CommentList from '../comment/CommentList.vue';

@Component({
  components: {
    UserLink,
    TextEditor,
    NovelTag,
    CommentList,
  },
})
export default class NovelDetailPage extends Vue {
  dayjs = dayjs;

  get novelId() {
    return +(this.$route.params.id + '');
  }
  @Watch('novelId')
  onNovelIdChange() {
    this.novel = null;
    this.initNovel();
  }

  @Inject() userInfo!: UserInfo | null | undefined;

  errorMessage = '';
  novel: NovelInfo | null | undefined = void 0;
  async initNovel() {
    const resp = await getNovelById(this.novelId);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      this.errorMessage = '获取小说失败';
    } else {
      this.novel = resp.data;
      this.errorMessage = '';
    }
  }
  get coverUrl() {
    if (!this.novel?.cover) return './img/cover.png';
    return '/api/image/' + this.novel.cover;
  }
  get isMyNovel() {
    if (!this.userInfo?.id) return false;
    if (!this.novel?.author?.id) return false;
    return this.userInfo.id === this.novel.author.id;
  }

  editMode: 'tags' | 'description' | null = null;
  editForm: Partial<{
    tags: string;
    description: string;
  }> | null = null;
  startEditMode(mode: 'tags' | 'description') {
    if (!this.novel) return;
    this.editMode = mode;
    if (mode === 'tags') {
      this.editForm = {
        tags: this.novel.tags.join(', '),
      };
    } else {
      this.editForm = {
        description: this.novel.description,
      };
    }
  }
  async cancelEditMode() {
    this.editMode = null;
    this.editForm = null;
  }
  async submitTagEdit() {
    if (!this.novel || this.editForm?.tags == null) return;
    const tags = [...new Set(this.editForm.tags ? this.editForm.tags.split(/(?:(?:[,;，；、]\s*)+\s*)/) : [])];
    if (tags.length > 20 || tags.some(tag => tag.length > 15)) {
      ElMessage({ type: 'error', message: '标签应不超过 20 个，每个标签不超过 15 个字' });
      return;
    }
    const resp = await updateNovelTags(this.novel.id, tags);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    this.novel = resp.data;
    this.cancelEditMode();
  }
  async submitDescriptionEdit() {
    if (!this.novel || this.editForm?.description == null) return;
    const description = this.editForm.description;
    const resp = await updateNovelDescription(this.novel.id, description);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    this.novel = resp.data;
    this.cancelEditMode();
  }
  async uploadCover() {
    if (!this.novel) return;
    const file = await uploadFile('image/*');
    const resp = await updateNovelCover(this.novel.id, file);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    this.novel = resp.data;
    this.cancelEditMode();
  }

  async setFavorite(isFavorite: boolean) {
    if (!this.novel) return;
    const resp = await (isFavorite ? addFavorite : removeFavorite)(this.novel.id);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    this.initNovel();
  }

  viewToc: 'reverse' | 'normal' = 'reverse';
  get toc() {
    if (!this.novel?.chapters.length) return [];
    const list = this.novel.chapters.slice(1);
    if (this.viewToc === 'reverse') list.reverse();
    return list;
  }
  reverseToc() {
    this.viewToc = this.viewToc === 'reverse' ? 'normal' : 'reverse';
  }

  get commentListId() {
    if (!this.novel?.chapters.length) return [];
    return this.novel.chapters[0].id;
  }

  newChapterForm: CreateChapterFormData | null = null;
  startNewChapter() {
    this.newChapterForm = {
      title: '',
    };
  }
  async submitNewChapter() {
    if (!this.novel || !this.newChapterForm) return;
    const resp = await createChapter(this.novel.id, { title: this.newChapterForm.title });
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    this.newChapterForm = null;
    this.$router.push('/novel/' + this.novel.id + '/chapter/' + resp.data.id + '/edit');
  }


  editTitleForm: { title: string } | null = null;
  editTitle() {
    if (!this.novel) return;
    this.editTitleForm = {
      title: this.novel.title,
    };
  }
  async submitEditTitle() {
    if (!this.novel || !this.editTitleForm) return;
    const resp = await updateNovelTitle(this.novel.id, this.editTitleForm.title);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    this.editTitleForm = null;
    this.novel = resp.data;
  }

  get canManageNovel() {
    if (!this.userInfo || !this.novel) return false;
    if (this.userInfo.role === 'admin' || this.userInfo.role === 'mod') return true;
    return this.isMyNovel;
  }

  async deleteNovel() {
    if (!this.novel) return;

    const cont = await ElMessageBox.confirm( `确定要删除小说 "${this.novel.title}" 吗？此操作不可恢复。`, '删除小说', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => true, () => false);
    if (!cont) return;

    const resp = await deleteNovel(this.novel.id);
    if (resp.error) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }

    ElMessage({ type: 'success', message: '小说已删除' });
    this.$router.push('/');
  }

  mounted() {
    this.initNovel();
  }
}
</script>
<template>
<div class="novel-detail-page">
  <div class="error" v-if="errorMessage">{{ errorMessage }}</div>
  <div class="novel" v-if="novel">
    <div class="novel-title">
      <div class="novel-title-actions">
        <el-button class="novel-fav novel-fav-off" text icon="el-icon-star" v-if="!novel.is_favorite" @click="setFavorite(true)" />
        <el-button class="novel-fav novel-fav-on" text icon="el-icon-star-filled" v-else @click="setFavorite(false)" />
      </div>
      <h1>{{ novel.title }}</h1>
      <div class="novel-title-actions-right">
        <el-dropdown placement="bottom-end" v-if="canManageNovel">
          <el-button icon="el-icon-more"></el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="deleteNovel()"><span class="danger-item">删除小说</span></el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="novel-metadata">
      <div class="novel-metadata-cover">
        <div class="cover-container">
          <img :src="coverUrl" alt="" @click="isMyNovel && uploadCover()" />
          <el-button v-if="isMyNovel" class="upload-cover-button" icon="el-icon-picture" @click="uploadCover">上传封面图</el-button>
        </div>
      </div>
      <div class="novel-metadata-info">
        <div class="novel-metadata-line">
          <div class="novel-metadata-title">作者</div>
          <div class="novel-metadata-value">
            <user-link :user="novel.author" author />
          </div>
        </div>
        <div class="novel-metadata-line">
          <div class="novel-metadata-title">最近更新</div>
          <div class="novel-metadata-value">
            <time :datetime="novel.updated_at">{{ novel.updated_at ? dayjs(novel.updated_at).format('YYYY年MM月DD日 HH:mm') : '--' }}</time>
          </div>
        </div>
        <div class="novel-metadata-block">
          <el-button class="novel-metadata-edit novel-tags-edit" v-if="isMyNovel && editMode == null" icon="el-icon-edit" @click="startEditMode('tags')">编辑</el-button>
          <el-button class="novel-metadata-edit novel-tags-edit" v-if="isMyNovel && editMode === 'tags'" icon="el-icon-check" @click="submitTagEdit">保存</el-button>
          <el-button class="novel-metadata-edit novel-tags-edit" v-if="isMyNovel && editMode === 'tags'" icon="el-icon-close" @click="cancelEditMode">取消</el-button>
          <div class="novel-metadata-title novel-tags-title">标签</div>
          <div class="novel-metadata-value" v-if="editMode !== 'tags'">
            <div v-if="!novel.tags.length" class="novel-tags-empty">作者未提供标签</div>
            <div v-else class="novel-tags-list">
              <novel-tag v-for="tag in novel.tags" :key="tag" :tag="tag" />
            </div>
          </div>
          <div class="novel-metadata-value" v-if="editMode === 'tags'">
            <el-input class="novel-tags-input" v-model="editForm!.tags" placeholder="小说标签，用逗号分隔" />
          </div>
        </div>
      </div>
      <div class="novel-description">
        <el-button class="novel-metadata-edit novel-description-edit" v-if="isMyNovel && editMode == null" icon="el-icon-edit" @click="startEditMode('description')">编辑</el-button>
        <el-button class="novel-metadata-edit novel-description-edit" v-if="isMyNovel && editMode === 'description'" icon="el-icon-close" @click="cancelEditMode">取消</el-button>
        <el-button class="novel-metadata-edit novel-description-edit" v-if="isMyNovel && editMode === 'description'" icon="el-icon-check" @click="submitDescriptionEdit">保存</el-button>
        <div class="novel-description-title">小说简介</div>
        <text-editor v-if="editMode !== 'description'" readonly :model-value="novel.description" />
        <text-editor v-if="editMode === 'description'" v-model="editForm!.description" />
      </div>
    </div>
    <div class="novel-toc">
      <div class="novel-toc-title-row">
        <span class="novel-toc-title">目录</span>
        <el-button class="novel-toc-reverse" icon="el-icon-sort" @click="reverseToc">{{ viewToc === 'reverse' ? '按最新章节倒序' : '按章节顺序排列' }}</el-button>
      </div>
      <el-button class="novel-new-chapter" icon="el-icon-plus" v-if="isMyNovel" @click="startNewChapter">追加新章节</el-button>
      <div v-if="!toc.length" class="novel-toc-empty">暂无内容</div>
      <ol v-else class="novel-toc-list">
        <li class="novel-toc-list-item" v-for="chapter in toc" :key="chapter.id">
          <router-link class="novel-toc-list-item-link" :to="'/novel/' + novel.id + '/chapter/' + chapter.id">
            <span v-if="!chapter.visibility" class="novel-toc-list-item-hidden"><el-icon><el-icon-hide /></el-icon></span>
            <span class="novel-toc-list-item-title">{{ chapter.title }}</span>
            <time class="novel-toc-list-item-time" :datetime="chapter.updated_at">{{ chapter.updated_at ? dayjs(chapter.updated_at).format('YYYY年MM月DD日 HH:mm') : '--' }}</time>
          </router-link>
          <router-link v-if="isMyNovel" class="novel-toc-list-item-edit" :to="'/novel/' + novel.id + '/chapter/' + chapter.id + '/edit'">
            <el-icon><el-icon-edit /></el-icon>&nbsp;编辑
          </router-link>
        </li>
      </ol>
    </div>
    <comment-list :cid="commentListId" :author="novel.author" />
  </div>
  <el-dialog model-value v-if="editTitleForm" title="修改小说标题" @close="editTitleForm = null">
    <el-form class="new-chapter-form" :model="editTitleForm" ref="editTitleForm">
      <el-form-item prop="title" required>
        <el-input v-model="editTitleForm.title" placeholder="小说标题" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button icon="el-icon-close" @click="editTitleForm = null">取消</el-button>
      <el-button type="primary" icon="el-icon-check" @click="submitEditTitle">更新小说标题</el-button>
    </template>
  </el-dialog>
  <el-dialog model-value v-if="newChapterForm" title="创建新章节" @close="newChapterForm = null">
    <el-form class="new-chapter-form" :model="newChapterForm" ref="newChapterForm">
      <el-form-item prop="title" required>
        <el-input v-model="newChapterForm.title" placeholder="章节标题" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button icon="el-icon-close" @click="newChapterForm = null">取消创建</el-button>
      <el-button type="primary" icon="el-icon-check" @click="submitNewChapter">开始编辑</el-button>
    </template>
  </el-dialog>
</div>
</template>
<style scoped>
.novel-detail-page {
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
  background-color: var(--el-bg-color-overlay);
  color: var(--el-text-color-primary);
  display: flow-root;
}
.tiny-mode .novel-detail-page {
  padding: 0 10px;
}

.novel-title {
  margin-bottom: 20px;
  display: flex;
}

.danger-item {
  color: var(--el-color-danger);
}

.novel-fav {
  background: none;
  padding: 3px;
  margin: 0 10px 0 0;
  float: left;
  font-size: 24px;
}

.novel-fav-on {
  color: var(--el-color-warning);
  font-size: 30px;
  padding: 0;
}

.novel-fav.novel-fav.novel-fav,
.novel-fav.novel-fav.novel-fav:hover {
  background: none;
}

.novel-title h1 {
  margin: 0;
  flex: 1;
  font-size: 150%;
  font-weight: bold;
}

.novel-metadata {
  display: grid;
  gap: 10px;
  grid-template-columns: auto 1fr;
  grid-template-rows: auto 1fr;
  grid-template-areas: "cover info" "cover description";
}

.thin-mode .novel-metadata {
  grid-template-areas: "cover info" "description description";
}

.novel-metadata-cover {
  grid-area: cover;
  position: relative;
}

.cover-container {
  position: relative;
}

.novel-metadata-cover img {
  width: 300px;
}

.thin-mode .novel-metadata-cover img {
  width: 100px;
}

.upload-cover-button {
  position: absolute;
  left: 50%;
  bottom: 20px;
  margin: 0 auto;
  transform: translateX(-50%);
  background: var(--el-bg-color);
}

.cover-container:not(:hover):not(:focus-within) .upload-cover-button {
  visibility: hidden;
}

.thin-mode .upload-cover-button {
  bottom: 0;
}

.novel-metadata-info {
  grid-area: info;
}

.novel-metadata-line,
.novel-metadata-block {
  margin-top: 5px;
}

.novel-metadata-line {
  display: flex;
  line-height: 30px;
}

.novel-metadata-line .novel-metadata-title {
  flex: 0 0 5em;
}

.novel-metadata-title {
  font-size: 120%;
  font-weight: bold;
}

.novel-metadata-block .novel-metadata-value {
  margin-top: 5px;
  margin-left: 2em;
}

.novel-metadata-edit {
  float: right;
  margin-left: 0.5em;
}

.tiny-mode .novel-metadata-edit :deep(span) {
  display: none;
}

.novel-tags-empty {
  color: var(--el-text-color-secondary);
}

.novel-tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.novel-toc {
  margin-top: 20px;
}

.novel-description {
  grid-area: description;
}

.novel-description-title {
  font-size: 120%;
  font-weight: bold;
  margin-bottom: 10px;
}

.novel-toc-title-row {
  margin-bottom: 10px;
  line-height: 40px;
}

.novel-toc-title {
  font-size: 120%;
  font-weight: bold;
}

.novel-toc-reverse {
  margin-left: 1em;
}

.novel-toc-empty {
  margin-bottom: 10px;
  color: var(--el-text-color-secondary);
}

.novel-toc-list {
  list-style: none;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.novel-toc-list-item {
  display: flex;
}

.novel-toc-list-item-link,
.novel-toc-list-item-edit {
  color: var(--el-color-text);
  padding: 5px 20px;
  border: 1px solid var(--el-border-color-light);
  border-radius: var(--el-border-radius-base);
  text-decoration: none;
  align-content: center;
}
.novel-toc-list-item-link {
  flex: 1;
}
.novel-toc-list-item-link :deep(.el-icon),
.novel-toc-list-item-edit :deep(.el-icon) {
  vertical-align: -0.1em;
}


.novel-toc-list-item-link:hover,
.novel-toc-list-item-edit:hover {
  color: var(--el-color-primary);
  box-shadow: var(--el-box-shadow-light);
}

.novel-toc-list-item-title {
  display: inline;
}

.novel-toc-list-item-time {
  color: var(--el-text-color-secondary);
  float: right;
  white-space: nowrap;
}

.novel-new-chapter {
  margin: 10px 0;
  width: 100%;
  display: block;
}

.error {
  padding: 100px 0;
  text-align: center;
  color: var(--el-text-color-secondary);
}

.novel-title-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}
</style>
